<?php

namespace app\services;
use app\Exception\CaptchaException;

class CaptchaService
{
    public static function generateCaptcha($ip)
    {
        try {
            $str ='ABCDEFGHJKMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            $randStr = str_shuffle($str);
            $rands = str_shuffle(substr($randStr, 0, 4));
    
            if(!self::captchaSendIp($ip, $rands))
                throw new CaptchaException(['status' => 302, 'errorMsg' => '请求过于频繁,3分钟后在请求', 'errorCode' => 10301]);
    
            return $rands;
        }catch (\Exception $e) {
            throw $e->getMessage();
        }
    }

    private static function captchaSendIp($ip, $code)
    {
        $redis = new RedisService();
        // $redis->flushAll();exit;

        if($redis->exists('blackListOfIp-'.$ip)){
            return false;
        }

        $cacheKey = $redis->get('sendIpTimes-'.$ip);
        if($cacheKey){
            $redis->increment('sendIpTimes-'.$ip);
            if($cacheKey >= 60 ){
                $redis->set('blackListOfIp-'.$ip, 1, 180);
                return false;
            }
        }else{
            $redis->set('sendIpTimes-'.$ip, 1, 360);
        }

        $redis->set('sendIpCode-'.$ip, json_encode($code), 180);
        return true;
    }

    public static function verification($code, $ip)
    {
        $redis = new RedisService();
        
        $cacheValue = $redis->get('sendIpCode-'. $ip);
        if($cacheValue){
            $captcha = strtolower($cacheValue);
            if($captcha != $code){
                throw new CaptchaException(['status' => 302, 'errorMsg' => '验证码错误！', 'errorCode' => 10302]);
            }
        }else{
            throw new CaptchaException(['status' => 302, 'errorMsg' => '验证码已过期！', 'errorCode' => 10303]);
        }
        
    }
}